package com.dzh.controller;

import com.dzh.mapper.AdminTicketMapper;
import com.dzh.mapper.QppriorityMapper;
import com.dzh.mapper.TicketMapper;
import com.dzh.mapper.UserTicketMapper;
import com.dzh.pojo.Qppriority;
import com.dzh.pojo.Ticket;
import com.dzh.pojo.Tour;
import com.dzh.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.server.Session;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Controller


public class AdminController {
    @Autowired
    AdminTicketMapper adminTicketMapper;
    @Autowired
    QppriorityMapper qppriorityMapper;
    @Autowired
    UserTicketMapper userTicketMapper;
    @Autowired
    TicketMapper ticketMapper;

    @RequestMapping("/admin")
    public String admin(Model model, HttpSession session, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        String username =(String) session.getAttribute("loginUser");

        if(username==null){
            out.println("<script>alert('你尚未登录请先登录');</script>");
            return "login";
        }
      else  if(username.equals("admin")){
            return "admin";
        }
        else{
            out.println("<script>alert('你不是管理员哦');</script>");
            return "index";
        }

    }

    @RequestMapping("/todeleteguke")
    public String todeleteguke(Model model){
        return "deleteguke";
    }

    @RequestMapping("/deleteguke")
    public String deleteguke(Model model,String username,HttpSession session,HttpServletResponse response) throws IOException {
          adminTicketMapper.deleteguke(username);
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        out.println("<script>alert('删除用户成功');</script>");
        return "admin";
    }


    @RequestMapping("/toupdateadminmm")
    public String toupdateadminmm(Model model){
        return "updateadminmm";
    }


    @RequestMapping("/updateadminmm")
    public String updateadminmm(Model model, User user,HttpSession session,HttpServletResponse response) throws IOException {
        adminTicketMapper.updateadminmm(user);
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        out.println("<script>alert('修改密码成功');</script>");
        return "admin";
    }

    @RequestMapping("/toaddticket")
    public String toaddticket(Model model){
        return "bancixinxi_add";
    }

    @RequestMapping("addticket")
    public String addticket(Model model, Ticket ticket,HttpSession session,HttpServletResponse response) throws IOException {
        adminTicketMapper.addticket(ticket);
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        out.println("<script>alert('票程添加成功');</script>");
        return "admin";
    }



    @RequestMapping("/todeleteticket")
    public String todeleteticket(Model model){
        return  "bancixinxi_delete";
    }

    @RequestMapping("/deleteticket")
    public String deleteticket(String tid,Model model,HttpSession session,HttpServletResponse response) throws IOException {
        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();
        adminTicketMapper.deleteticket(tid);
        ticketMapper.deleteTicketByAdmin(tid);
        qppriorityMapper.deleteTicketByAdmin(tid);
        out.println("<script>alert('票程删除成功');</script>");
        return "admin";
    }


    @RequestMapping("/toadminlist")
    public String toadminlist(Model model){
     List<Ticket> tickets =  ticketMapper.queryAllList();
     model.addAttribute("newtickets",tickets);
     return "bancixinxi_admin_list";
    }

    @RequestMapping("/toupdateadmin")
    public String toupdateadmin (Model model,String tid,String chufadi,String mudidi,String gdate,String adate,String gtime,String atime,String type,int yupiao,int money,HttpSession session){
        model.addAttribute("tid",tid);
        model.addAttribute("chufadi",chufadi);
        model.addAttribute("mudidi",mudidi);
        model.addAttribute("gdate",gdate);
        model.addAttribute("gtime",gtime);
        model.addAttribute("adate",adate);
        model.addAttribute("atime",atime);
        model.addAttribute("yupiao",yupiao);
        model.addAttribute("type",type);
        model.addAttribute("money",money);
        session.setAttribute("yuantid",tid);
        session.setAttribute("yuanyupiao",yupiao);
        return "bancixinxi_update";
    }


    @RequestMapping("/updateticketadmin")
    public String updateticketadmin(Model model,HttpSession session,String tid,String chufadi,String mudidi,String gdate,String gtime,String adate,String atime,int money,int yupiao,String type,HttpServletResponse response) throws IOException {
      String tid1 =(String) session.getAttribute("yuantid");
      int yupiao1 = (int) session.getAttribute("yuanyupiao");

        response.setContentType("text/html;utf8");
        response.setCharacterEncoding("utf8");
        PrintWriter out=response.getWriter();


     int o = qppriorityMapper.queryfirstpriority(tid1);
     if(o==0){
        userTicketMapper.updateTidByAdmin(tid,tid1);
        qppriorityMapper.updateTidByAdmin(tid,tid1);
         ticketMapper.updateTicketByAdmin(tid,chufadi,mudidi,gdate,gtime,adate,atime,money,yupiao,type,tid1);
     }
     else{
             if(o>=yupiao){
                 for(int i=0;i<yupiao;i++){

                     Qppriority qppriority =     qppriorityMapper.queryprioritymin(tid1);
                     String username = qppriority.getUsername();
                     int priority = qppriority.getPriority();
                     qppriorityMapper.deletePriority(priority,tid1);
                     userTicketMapper.addUserTicket(username,tid);

                 }
                 qppriorityMapper.updateTidByAdmin(tid,tid1);
                 ticketMapper.updateTicketByAdmin(tid,chufadi,mudidi,gdate,gtime,adate,atime,money,0,type,tid1);

             }
             else{
                 for(int i =0;i<o;i++){

                Qppriority qppriority =     qppriorityMapper.queryprioritymin(tid1);
                String username = qppriority.getUsername();
                int priority = qppriority.getPriority();
                qppriorityMapper.deletePriority(priority,tid1);
                userTicketMapper.addUserTicket(username,tid);

                 }
                 ticketMapper.updateTicketByAdmin(tid,chufadi,mudidi,gdate,gtime,adate,atime,money,yupiao-o,type,tid1);

             }
     }
        out.println("<script>alert('票程修改成功');</script>");
      return "admin";
    }









    @RequestMapping("/toaddtour")
    public String toaddtour(Model model){

        return "submit";
    }

    @RequestMapping("/addtour")
    public String addtour(@RequestParam("tourimg1") MultipartFile srcFile, @RequestParam("tourimg2")MultipartFile srcFile2, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) throws IOException {



        //前端没有选择文件，srcFile为空
//选择了文件，开始上传操作
        try {
//构建上传目标路径，找到了项目的target的classes目录
            File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
            if(!destFile.exists()) {
                destFile = new File("");
            }
//输出目标文件的绝对路径
            System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路径
            SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
            String times = sf_.format(new Date());
            File upload = new File(destFile.getAbsolutePath(), "static/images/resource");
//若目标文件夹不存在，则创建
            if(!upload.exists()) {
                upload.mkdirs();
            }
            System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile);
            System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile2);
//根据srcFile大小，准备一个字节数组
            byte[] bytes = srcFile.getBytes();
            byte[] bytes2 = srcFile2.getBytes();
//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通过项目路径，拼接上传路径
            Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
            Path path2 = Paths.get(upload.getAbsolutePath()+"/"+srcFile2.getOriginalFilename());
//** 开始将源文件写入目标地址
            Files.write(path, bytes);
            Files.write(path2, bytes2);
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
            String fileName = srcFile.getOriginalFilename();
            String fileName2 = srcFile2.getOriginalFilename();
// 获得文件后缀名称
            String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
            String suffixName2 = fileName2.substring(fileName2.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
//            String newFileName = uuid + "."+ suffixName;
//            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
            System.out.println(fileName);
            System.out.println(path);
            String aaa ="images/resource/";
            String bbb1 = aaa+fileName;
            String bbb2 = aaa+fileName2;
            System.out.println(bbb1);
            System.out.println(bbb2);


            String tourid = request.getParameter("tourid");
            String tourname = request.getParameter("tourname");
            String tourbackground = request.getParameter("tourbackground");
            String tourstrategy = request.getParameter("tourstrategy");
            String tourtime = request.getParameter("tourtime");
            String tourday = request.getParameter("tourday");
            String tournotice = request.getParameter("tournotice");
            int tourmoney =  Integer.parseInt(request.getParameter("tourmoney"));
            String tourplace = request.getParameter("tourplace");
            int tourrecommend =  Integer.parseInt(request.getParameter("tourecommend"));
            String tourphone = request.getParameter("tourphone");
            String tourcity = request.getParameter("tourcity");
      System.out.println(tourrecommend);
            Tour tour1 = new Tour(tourid,tourname,bbb1,bbb2,tourbackground,tourstrategy,tourday,tournotice,tourphone,tourmoney,tourrecommend,tourplace,tourtime,tourcity);
          adminTicketMapper.addTour(tour1);





    } catch (IOException e) {
            e.printStackTrace();
        }



        return "admin";
}



@RequestMapping("/todeletetour")
    public String todeletetour(Model model){
        return "tourdelete";
}


@RequestMapping("/deletetour")
    public String deletetour(Model model,String tourname){
        adminTicketMapper.deleteTour(tourname);
        return "admin";
}




@RequestMapping("/toupdatetour")
    public String toupdatetour(Model model){
        return "totourupdate";

}

@RequestMapping("/tourupdate")
    public String tourupdate(Model model,String tourname,HttpSession session){
    Tour tour =    adminTicketMapper.querytourByTourname(tourname);
    String tourid1 = tour.getTourid();
    session.setAttribute("tourid1",tourid1);
    model.addAttribute("tour",tour);
    return "tourupdate";

}


@RequestMapping("/updatetour")
    public String updatetour(@RequestParam("tourimg1") MultipartFile srcFile, @RequestParam("tourimg2")MultipartFile srcFile2, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model,HttpSession session) throws IOException{



    //前端没有选择文件，srcFile为空
//选择了文件，开始上传操作
    try {
//构建上传目标路径，找到了项目的target的classes目录
        File destFile = new File(ResourceUtils.getURL("classpath:").getPath());
        if(!destFile.exists()) {
            destFile = new File("");
        }
//输出目标文件的绝对路径
        System.out.println("file path:"+destFile.getAbsolutePath());
//拼接子路径
        SimpleDateFormat sf_ = new SimpleDateFormat("yyyyMMddHHmmss");
        String times = sf_.format(new Date());
        File upload = new File(destFile.getAbsolutePath(), "static/images/resource");
//若目标文件夹不存在，则创建
        if(!upload.exists()) {
            upload.mkdirs();
        }
        System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile);
        System.out.println("完整的上传路径："+upload.getAbsolutePath()+"/"+srcFile2);
//根据srcFile大小，准备一个字节数组
        byte[] bytes = srcFile.getBytes();
        byte[] bytes2 = srcFile2.getBytes();
//拼接上传路径
//Path path = Paths.get(UPLOAD_FOLDER + srcFile.getOriginalFilename());
//通过项目路径，拼接上传路径
        Path path = Paths.get(upload.getAbsolutePath()+"/"+srcFile.getOriginalFilename());
        Path path2 = Paths.get(upload.getAbsolutePath()+"/"+srcFile2.getOriginalFilename());
//** 开始将源文件写入目标地址
        Files.write(path, bytes);
        Files.write(path2, bytes2);
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
// 获得文件原始名称
        String fileName = srcFile.getOriginalFilename();
        String fileName2 = srcFile2.getOriginalFilename();
// 获得文件后缀名称
        String suffixName = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
        String suffixName2 = fileName2.substring(fileName2.lastIndexOf(".") + 1).toLowerCase();
// 生成最新的uuid文件名称
//            String newFileName = uuid + "."+ suffixName;
//            redirectAttributes.addFlashAttribute("message", "文件上传成功"+newFileName);
        System.out.println(fileName);
        System.out.println(path);
        String aaa ="images/resource/";
        String bbb1 = aaa+fileName;
        String bbb2 = aaa+fileName2;
        System.out.println(bbb1);
        System.out.println(bbb2);

      String tourid1 =(String) session.getAttribute("tourid1");
        String tourid = request.getParameter("tourid");
        String tourname = request.getParameter("tourname");
        String tourbackground = request.getParameter("tourbackground");
        String tourstrategy = request.getParameter("tourstrategy");
        String tourtime = request.getParameter("tourtime");
        String tourday = request.getParameter("tourday");
        String tournotice = request.getParameter("tournotice");
        int tourmoney =  Integer.parseInt(request.getParameter("tourmoney"));
        String tourplace = request.getParameter("tourplace");
        int tourrecommend =  Integer.parseInt(request.getParameter("tourecommend"));
        String tourphone = request.getParameter("tourphone");
        String tourcity = request.getParameter("tourcity");


        adminTicketMapper.updateTour(tourid,tourname,bbb1,bbb2,tourbackground,tourstrategy,tourday,tournotice,tourphone,tourmoney,tourrecommend,tourplace,tourtime,tourcity,tourid1);


    } catch (IOException e) {
        e.printStackTrace();
    }



        return "admin";


}






}
